package com.lanxin.controller;

import com.lanxin.vo.ResponseBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by cyh on 2021/3/18.
 */

@RestController
public class LoginController {

    @RequestMapping("login")
    public ResponseBean login(String username,String password){

        ResponseBean responseBean = null;
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            Subject subject =  SecurityUtils.getSubject();
            subject.login(token);
            if(subject.isAuthenticated()){
                responseBean = new ResponseBean(200,"登录成功");
            }
        } catch (IncorrectCredentialsException e) {
            responseBean = new ResponseBean(500,"密码错误");
        }
        catch (AuthenticationException e) {
            responseBean = new ResponseBean(500,"用户名不存在");
        }
        catch (Exception e) {
            responseBean = new ResponseBean(500,"登录失败");
        }
        return responseBean;
    }

    @RequestMapping("logOut")
    public ResponseBean logOut(){
        Subject subject =  SecurityUtils.getSubject();
        subject.logout();
        return new ResponseBean(200,"退出成功");
    }

    @RequestMapping("unauth")
    public ResponseBean unauth(){
        return new ResponseBean(403,"没有权限");
    }
}
